<template>
    <div>
        <div>
            <f-table
                id="resourceSortListss"
                ref="tableRef"
                row-key="id"
                :fetch="fetch"
                :columns="columns"
                :scroll="{ x: 'max-content' }"
                :row-selection="{
                    selectedRowKeys,
                    onChange: handleCheck,
                    getCheckboxProps,
                    preserveSelectedRowKeys: true,
                }"
                :resize-scroll-gap="16 + 1 + 24"
            >
                <template #higherSearchStatic="{ model }">
                    <a-row :gutter="32">
                        <a-col :span="12">
                            <a-form-item name="name">
                                <div class="higher-search-item">
                                    <span class="higher-search-item-label">资源包名称</span>
                                    <a-input
                                        v-model:value="model.name"
                                        placeholder="资源包名称"
                                        allow-clear
                                    />
                                </div>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item name="version">
                                <div class="higher-search-item">
                                    <span class="higher-search-item-label">资源包版本</span>
                                    <a-input
                                        v-model:value="model.version"
                                        placeholder="请输入资源包版本"
                                        allow-clear
                                    />
                                </div>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </template>
                <template #higherSearchExpandable="{ model }">
                    <a-row :gutter="32">
                        <a-col :span="12">
                            <a-form-item name="create_username">
                                <div class="higher-search-item">
                                    <span class="higher-search-item-label">创建人</span>
                                    <a-input
                                        v-model:value="model.create_username"
                                        placeholder="请输入创建人"
                                        allow-clear
                                    />
                                </div>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item name="fondtime">
                                <div class="higher-search-item">
                                    <span class="higher-search-item-label">时间范围</span>
                                    <a-range-picker
                                        v-model="rangeTime"
                                        style="width: 900px"
                                        show-time
                                        format="YYYY-MM-DD HH:mm:ss"
                                        :placeholder="['开始时间', '结束时间']"
                                        @change="updateTimeChange"
                                    />
                                </div>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </template>

                <template #toolbar>
                    <a-upload-dragger
                        v-model:file-list="fileList"
                        accept=".yaml"
                        name="file"
                        :show-upload-list="false"
                        :before-upload="beforeUpload"
                    >
                        <a-button type="primary" :loading="isLoading" class="upload-files">
                            <upload-outlined></upload-outlined>
                            上传yaml文件
                        </a-button>
                    </a-upload-dragger>

                    <a-button type="primary" style="display: none">批量删除</a-button>

                    <span v-if="selectedRows.length > 0">
                        已选择
                        <span class="number-background">{{ selectedRows.length }}</span>
                        项
                    </span>
                </template>
                <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'operation'">
                        <span class="table-action">
                            <a-button type="link" @click="showModalPreview1(record)">
                                编辑
                            </a-button>

                            <a-button type="link" @click="showModalPreview(record)">
                                预览
                            </a-button>
                            <a-button type="link" @click="delectModal(record)"> 删除 </a-button>
                        </span>
                    </template>
                </template>
            </f-table>
        </div>
        <a-modal
            v-model:open="open"
            title="请问确定要删除吗？"
            ok-text="确定"
            centered
            cancel-text="取消"
            @ok="handleDelect"
        >
        </a-modal>

        <a-modal
            v-model:open="openPreview"
            cancel-text="取消"
            centered
            width="77vw"
            title="预览"
            :mask-closable="false"
            :body-style="{ overflow: 'hidden' }"
            :style="{ maxWidth: '1200px' }"
            class="fixed-modal"
        >
            <template #footer>
                <a-button key="back" @click="handlecancel">取消</a-button>
            </template>
            <div class="marmodal">
                <marginModal :name="sendname" :array-props="result" />
            </div>
        </a-modal>

        <a-modal
            v-model:open="openPreview1"
            ok-text="确定"
            cancel-text="取消"
            centered
            width="77vw"
            title="编辑"
            :mask-closable="false"
            @ok="handleOkPreview1"
            :body-style="{ overflow: 'hidden' }"
            :style="{ maxWidth: '1200px' }"
            class="fixed-modal"
        >
            <div class="marmodal">
                <one :name="sendname" :array-props="result" />
            </div>
        </a-modal>
    </div>
</template>

<script setup>
import { computed, ref } from 'vue';

import { UploadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { omit } from 'lodash-es';

// 导入预览外层组件
import marginModal from '@/components/modalComponent/marginmodal.vue';
import one from '@/components/sortClassUpdate/one.vue';
import service from '@/service';
import pinia from '@/store';
import useCounter from '@/store/counter';

const counterStore = useCounter(pinia);
const beforeUpload = (file) => {
    handleUploadChange(file);

    return false;
};
// 上传文件
const isLoading = ref(false);
const handleUploadChange = async (file) => {
    try {
        const formData = new FormData();

        formData.append('file', file);

        const res = await service.post(`/warpTemplate?username=${counterStore.username}`, formData);

        if (res === 'success') {
            message.success('yaml文件上传成功');
            tableRef.value.refresh();
        }
    } catch (error) {
        message.error(error);
    }
};
// 选中部分
const tableRef = ref(null);

const selectedRowKeys = computed(() => selectedRows.value.map((row) => row.name));
let selectedRows = ref([]);
const handleCheck = (_, rows) => {
    selectedRows.value = rows;
};
const getCheckboxProps = (row) => {
    return {
        disabled: row.name,
    };
};

// 编辑

const openPreview1 = ref(false);

const showModalPreview1 = async (record) => {
    try {
        sendname.value = record.name;

        const baseUrl = '/warpTemplate';

        const fullUrl = `${baseUrl}/${record.name}`;

        const res = await service.get(fullUrl);

        if (res) {
            openPreview1.value = true;
        }

        const { data, sort } = res;

        const loop = (cSort, cdata) => {
            const ndata = cdata;

            return cSort.children.reduce((prev, curr) => {
                const tdata = ndata[curr.name];

                if (!tdata) {
                    return prev;
                }

                if (
                    ['string', 'int', 'ico', 'svg', 'png', 'bool', '', 'exe', 'pem'].includes(
                        tdata.type,
                    )
                ) {
                    prev.push(tdata);
                } else if (tdata.type === 'object') {
                    prev.push({
                        ...tdata,
                        value: loop(curr, tdata.value),
                    });
                }

                return prev;
            }, []);
        };

        result.value = loop(sort, data);
    } catch (error) {
        message.error(error);
    }
};
const handleOkPreview1 = () => {
    openPreview1.value = false;
};
/*
 * 预览
 */

const openPreview = ref(false);
const result = ref([]);
const sendname = ref('');
const showModalPreview = async (record) => {
    try {
        sendname.value = record.name;

        const baseUrl = '/warpTemplate';

        const fullUrl = `${baseUrl}/${record.name}`;

        const res = await service.get(fullUrl);

        if (res) {
            openPreview.value = true;
        }

        const { data, sort } = res;

        const loop = (cSort, cdata) => {
            const ndata = cdata;

            return cSort.children.reduce((prev, curr) => {
                const tdata = ndata[curr.name];

                if (!tdata) {
                    return prev;
                }

                if (
                    ['string', 'int', 'ico', 'svg', 'png', 'bool', '', 'exe', 'pem'].includes(
                        tdata.type,
                    )
                ) {
                    prev.push(tdata);
                } else if (tdata.type === 'object') {
                    prev.push({
                        ...tdata,
                        value: loop(curr, tdata.value),
                    });
                }

                return prev;
            }, []);
        };

        result.value = loop(sort, data);
    } catch (error) {
        message.error(error);
    }
};
const handlecancel = () => {
    openPreview.value = false;
};

// 删除
const ziyuanbaoname = ref('');
const open = ref(false);
const delectModal = (record) => {
    open.value = true;
    ziyuanbaoname.value = record.name;
};
const handleDelect = async () => {
    try {
        const params = {
            template_name: ziyuanbaoname.value,
        };
        const res = await service.delete('/warpTemplate', params);

        if (res) {
            message.success('删除成功');
            open.value = false;

            tableRef.value.refresh();
        }
    } catch (error) {
        message.error('该模板不可删除，还有资源包正在使用');
    }
};

// 选择时间范围部分
const rangeTime = ref(null);
const startTime = ref('');
const endTime = ref('');
const updateTimeChange = (value, dateString) => {
    startTime.value = dateString[0];
    endTime.value = dateString[1];
};
const columns = [
    {
        title: '资源包类型名称',
        dataIndex: 'name',
        width: 250,
    },
    {
        title: '资源包版本',
        dataIndex: 'version',
        width: 250,
    },

    {
        title: '创建人',
        dataIndex: 'create_username',
        width: 250,
    },
    {
        title: '创建时间',
        dataIndex: 'create_at',
        width: 250,
    },

    {
        title: '操作',
        dataIndex: 'operation',
        fixed: 'right',
        width: '20%',
    },
];

const fileList = ref([]);

const fetch = async (params) => {
    try {
        const res = await service.get('/warpTemplate', {
            ...omit(params, ['page', 'pageSize']),
            offset: (params.page - 1) * params.pageSize,
            limit: params.pageSize,
            startTime: startTime.value,
            endTime: endTime.value,
        });

        return Promise.resolve({
            dataSource: res.data,
            total: res.total,
        });
    } catch (error) {
        message.error(error);
    }
};
</script>

<style lang="scss" scoped>
.fixed-modal {
    .ant-modal-content {
        max-width: 1200px;
        overflow: hidden;
        display: flex;
        flex-direction: column;

        .ant-modal-body {
            flex: 1;
            overflow: auto;
            padding: 24px;
        }
    }
}

.upload-files {
    color: #fff;
    margin: 0 15px;
}

.full-modal {
    overflow-y: scroll;
    .ant-modal {
        width: 100%;
        height: 1000px;
        background-color: #fff;
        top: 0;
        padding-bottom: 0;
        margin-top: -100px;
    }
    .ant-modal-content {
        top: 0;
        padding: 0;
        margin: 0;
        display: flex;
        flex-direction: column;
        height: calc(100vh);
    }

    .ant-modal-body {
        flex: 1;
    }
}

.marmodal {
    max-height: 77vh;
    overflow: auto;
    font-size: 16px;
}
</style>
